package com.yunxin.core.application.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunxin.common.exception.BusinessException;
import com.yunxin.core.application.dto.merchant.MerchantUserAccountInfoDTO;
import com.yunxin.core.application.dto.team.*;
import com.yunxin.core.application.service.TeamService;
import com.yunxin.core.application.service.UserTeamShipService;
import com.yunxin.core.domain.model.team.Team;
import com.yunxin.core.infra.persistence.mapper.team.SysTeamMapper;
import com.yunxin.core.infra.persistence.mapper.user.UserTeamShipMapper;
import com.yunxin.core.wechat.domain.WechatInfo;
import com.yunxin.core.wechat.domain.WechatInfoTeam;
import com.yunxin.core.wechat.service.WechatInfoService;
import com.yunxin.core.wechat.service.WechatInfoTeamService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class TeamServiceImpl extends ServiceImpl<SysTeamMapper, Team> implements TeamService {

    @Autowired
    private UserTeamShipService userTeamShipService;

    @Autowired
    private UserTeamShipMapper userTeamShipMapper;

    @Autowired
    private WechatInfoService wechatInfoService;
    @Autowired
    private WechatInfoTeamService wechatInfoTeamService;

    @Override
    public IPage<Team> getTeamPage(TeamPageCommand command) {
        QueryWrapper<Team> wrapper = new QueryWrapper<>();
        wrapper.like(command.getKeywords() != null, "team_name", command.getKeywords());
        wrapper.eq( "is_del", 1).eq( !ObjectUtils.isEmpty(command.getMerchantId()),"merchant_id", command.getMerchantId()).orderByDesc("create_time");
        Page<Team> objectPage = new Page<>(command.getPageNum(), command.getPageSize());
        Page<Team> teamPage = baseMapper.selectPage(objectPage, wrapper);
        List<Team> records = teamPage.getRecords();
        if (!ObjectUtils.isEmpty(records)){
            List<Integer> teamIds = records.stream().map(i -> i.getId()).toList();
            LambdaQueryWrapper<WechatInfoTeam> wechatInfoLambdaQueryWrapper=new LambdaQueryWrapper<>();
            wechatInfoLambdaQueryWrapper.in(WechatInfoTeam::getTeamId,teamIds);
            List<WechatInfoTeam> infoTeamList = wechatInfoTeamService.list(wechatInfoLambdaQueryWrapper);
            List<Long> wechatInfoIds = infoTeamList.stream().map(i -> i.getWechatInfoId()).toList();
            if (!ObjectUtils.isEmpty(wechatInfoIds)){
                List<WechatInfo> wechatInfos = wechatInfoService.listByIds(wechatInfoIds);
                Map<Long, WechatInfo> wechatInfoMap = wechatInfos.stream().collect(Collectors.toMap(WechatInfo::getId, obj -> obj));
                Map<Integer, Long> wtMap = infoTeamList.stream().collect(Collectors.toMap(WechatInfoTeam::getTeamId, obj -> obj.getWechatInfoId()));
                for (Team record : records) {
                    Long wechatInfoId = wtMap.get(record.getId());
                    if (!ObjectUtils.isEmpty(wechatInfoId)){
                        WechatInfo wechatInfo = wechatInfoMap.get(wechatInfoId);
                        if (!ObjectUtils.isEmpty(wechatInfo)){
                            record.setWechatInfoId(wechatInfo.getId());
                            record.setCorpName(wechatInfo.getCorpName());
                        }
                    }
                }
            }
        }

        return teamPage;
    }

    @Override
    public List<WechatInfoVO> wechatInfoList(String  corpName) {
        LambdaQueryWrapper<WechatInfo> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(!ObjectUtils.isEmpty(corpName),WechatInfo::getCorpName,corpName)
                .orderByDesc(WechatInfo::getCreateTime);
        List<WechatInfo> wechatInfoList = wechatInfoService.list(queryWrapper);
        List<WechatInfoVO> wechatInfoVOList=new ArrayList<>();
        for (WechatInfo wechatInfo : wechatInfoList) {
            WechatInfoVO wechatInfoVO=new WechatInfoVO();
            BeanUtils.copyProperties(wechatInfo,wechatInfoVO);
            wechatInfoVOList.add(wechatInfoVO);
        }
        return wechatInfoVOList;
    }

    @Override
    public Boolean add(TeamAddDTO dto) {
        // 先查
        QueryWrapper<Team> wrapper = new QueryWrapper<>();
        Team teamName = baseMapper.selectOne(wrapper
                .eq("team_name", dto.getTeamName()).eq("is_del", 1)
                .eq("merchant_id", dto.getMerchantId()));
        if(teamName!=null){
            throw new BusinessException("团队名称重复");
        }
        Team team = new Team();
        BeanUtil.copyProperties(dto,team);
        team.setCreateTime(new Date());
        team.setIsDel(1);
        boolean b = baseMapper.insert(team) > 0;
        if (!ObjectUtils.isEmpty(dto.getWechatInfoId())){
            WechatInfoTeam wechatInfoTeam=new WechatInfoTeam();
            wechatInfoTeam.setTeamId(team.getId());
            wechatInfoTeam.setWechatInfoId(dto.getWechatInfoId());
            wechatInfoTeam.setCreator(team.getCreator());
            wechatInfoTeamService.save(wechatInfoTeam);
        }
        return b;

    }

    @Override
    public boolean edit(TeamEditDTO dto) {
        Team team = baseMapper.selectOne(new QueryWrapper<Team>().eq("id", dto.getId()));
        if(team==null){
            throw new BusinessException("该团队不存在");
        }
        Team teamName = baseMapper.selectOne(new QueryWrapper<Team>()
                .eq("team_name", dto.getTeamName())
                .eq("is_del", 1)
                .eq("merchant_id", dto.getMerchantId()));
        if(teamName!=null && teamName.getId().longValue()!=dto.getId()){
            throw new BusinessException("团队名称重复");
        }
        BeanUtil.copyProperties(dto,team);
        team.setEditor(dto.getEditor());
        team.setUpdateTime(new Date());
        boolean b = baseMapper.updateById(team) > 0;
        if (!ObjectUtils.isEmpty(dto.getWechatInfoId())){
            LambdaQueryWrapper<WechatInfoTeam> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(WechatInfoTeam::getTeamId,team.getId());
            WechatInfoTeam wechatInfoTeam = wechatInfoTeamService.getOne(wrapper);
            if (ObjectUtils.isEmpty(wechatInfoTeam)){
                wechatInfoTeam=new WechatInfoTeam();
                wechatInfoTeam.setTeamId(team.getId());
                wechatInfoTeam.setCreator(team.getCreator());
            }else {
                wechatInfoTeam.setEditor(team.getEditor());
            }
            wechatInfoTeam.setWechatInfoId(dto.getWechatInfoId());
            wechatInfoTeamService.saveOrUpdate(wechatInfoTeam);
        }
        return b;
    }

    @Override
    public boolean editTeamStatus(Team team) {
        // 先查
        QueryWrapper<Team> wrapper = new QueryWrapper<>();
        Team t = baseMapper.selectOne(wrapper.eq("id", team.getId()));
        if(t==null){
            throw new BusinessException("该团队不存在");
        }
        BeanUtil.copyProperties(team,t);
        return baseMapper.updateById(team) > 0;

    }

    @Override
    public boolean delete(TeamDeleteDTO dto) {
        try {
            dto.getTeamIds().forEach(id->{
                // 先查
                QueryWrapper<Team> wrapper = new QueryWrapper<>();
                Team team = baseMapper.selectOne(wrapper.eq("id", id));
                if(team==null){
                    throw new BusinessException("该团队不存在");
                }
                team.setIsDel(2);
                baseMapper.updateById(team);
                // 同步删除团队关系
                userTeamShipService.deleteUserTeamByTeamId(id.longValue());

            });
        } catch (Exception e) {
            throw new BusinessException("删除团队失败");
        }
        return true;
    }

    @Override
    public List<Team> getTeamList(Long merchantId) {
        return baseMapper.selectList(new QueryWrapper<Team>().eq("is_del", 1) .eq("merchant_id", merchantId));
    }

    @Override
    public List<Team> getAllTeamList() {
        return baseMapper.selectList(new QueryWrapper<Team>().eq("is_del", 1));
    }

    @Override
    public Team selectTeamById(Long teamId) {
        return baseMapper.selectById(teamId);
    }


    /**
     * 团队管理员，根据userId查询团队信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<Team> getTeamListByUserId(Long userId) {
        return userTeamShipMapper.getTeamListByUserId(userId);
    }

    /**
     * 团队管理员只能看自己团队下的子账户
     *
     * @param userId
     * @return
     */
    @Override
    public List<MerchantUserAccountInfoDTO> getUserForTeamList(Long userId,List<Long> teamIds) {
        if (!ObjectUtils.isEmpty(userId)){
            return userTeamShipMapper.getUserForTeamList(userId);
        }else {
            return userTeamShipMapper.getUserForTeamListByTeamIds(teamIds);
        }

    }
}
